package com.iqiyi.pps.epg.web.webapp.action.program;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.iqiyi.pps.epg.api.model.web.program.TProgram;
import com.iqiyi.pps.epg.api.model.web.program.TProgramBase;
import com.iqiyi.pps.epg.api.model.web.query.TPage;
import com.iqiyi.pps.epg.core.dao.base.Page;
import com.iqiyi.pps.epg.core.model.channel.ChannelBase;
import com.iqiyi.pps.epg.core.service.channel.ChannelService;
import com.iqiyi.pps.epg.core.utils.Constants;
import com.iqiyi.pps.epg.core.utils.ApiHttpRequestUtil;
import com.iqiyi.pps.epg.web.utils.InnerApiUtil;
import com.iqiyi.pps.epg.web.utils.Struts2Utils;
import com.iqiyi.pps.epg.web.webapp.action.BaseAction;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.thrift.TSerializer;
import org.apache.thrift.protocol.TSimpleJSONProtocol;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by karkarrotxu on 2014/12/13.
 */

@Namespace("/program/program")
@Scope("prototype")
public class ProgramAction extends BaseAction<TProgram> {

    @Autowired
    private ChannelService channelService;

    private Page<TProgram> page;
    private TProgram entity;
    private Long id;
    private int fatherId;
    private JSONArray result;
    private List<ChannelBase> channelList;

    private static String checkFormat(String incence) {
        incence = incence.replaceAll("，", ",");
        incence = incence.replaceAll("：", ":");
        return incence;
    }

    public JSONArray getResult() {
        return result;
    }

    @Override
    @Action(value = "list", results = {@Result(name = "success", location = "/WEB-INF/content/program/program/list.jsp")})
    public String list() throws Exception {
        String fatherId = Struts2Utils.getParameter("fatherId");
        //    List<PropertyFilter> filters = PropertyFilter.buildFromHttpRequest(Struts2Utils.getRequest());
        // 设置默认排序方式
        if (!page.isOrderBySetted()) {
            page.setOrderBy("id");
            page.setOrder(Page.ASC);
        }
        TPage tPage = new TPage();
        tPage.setPageNo(page.getPageNo());
        tPage.setPageSize(page.getPageSize());
        tPage.setOrderBy(page.getOrderBy());
        tPage.setOrder(page.getOrder());


        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        Map<String, Object> headers = new HashMap<String, Object>();
        Map<String, Object> params = new HashMap<String, Object>();
        headers.put("Sign", InnerApiUtil.TEST_SIGN);
        params.put("fatherId", fatherId + "");
        boolean flag = true;
        if (flag) {
            calendar.add(Calendar.DATE, -3);
            String startDate = sdf.format(calendar.getTime());
            calendar.add(Calendar.DATE, 6);
            String endDate = sdf.format(calendar.getTime());
            params.put("startDate", startDate);
            params.put("endDate", endDate);
        } else {
            params.put("startDate", sdf.format(calendar.getTime()));
            params.put("endDate", sdf.format(calendar.getTime()));
        }

        params.put("pageSize", 300 + "");
        params.put("pageNo", 1 + "");

        String url = String.format(InnerApiUtil.BASE_URL, InnerApiUtil.PROGRAM_LIST);
        JSONObject tempJSON = (JSONObject) ApiHttpRequestUtil.forceGetSucData(url, headers, params);
        page.setPageSize(tempJSON.getIntValue("pageSize"));
        page.setPageNo(tempJSON.getIntValue("pageNo"));
        page.setTotalCount(tempJSON.getIntValue("totalCount"));
        result = tempJSON.getJSONArray("result");
        page.setResult(null);
        return SUCCESS;
    }

    public Page<TProgram> getPage() {
        return page;
    }

    public void setPage(Page<TProgram> page) {
        this.page = page;
    }

    @Override
    @Action(value = "input")
    public String input() throws Exception {
        channelList = channelService.getChannelBaseList();
        if (id != null && id.longValue() > 0) {
            System.out.println("entity id :" + id);
            Map<String, Object> headers = new HashMap<String, Object>();
            Map<String, Object> params = new HashMap<String, Object>();
            headers.put("Sign", InnerApiUtil.TEST_SIGN);
            params.put("id", id.longValue() + "");
            String url = String.format(InnerApiUtil.BASE_URL, InnerApiUtil.PROGRAM_LIST);
            JSONObject tempJSON = (JSONObject) ApiHttpRequestUtil.forceGetSucData(url, headers, params);
            if (tempJSON.getIntValue("totalCount") == 1) {
                entity = tempJSON.getJSONArray("result").getObject(0, TProgram.class);
            } else {
                entity = new TProgram();
            }
        } else {
            entity = new TProgram();
            entity.setFatherId(fatherId);
            entity.setAllowPopups(true);
            entity.setMemberFree(true);
            entity.setMemberOnly(false);
            for(ChannelBase channelBase : channelList ){
                if( channelBase.getId() == fatherId){
                    entity.setQitanId(channelBase.getQitanId());
                    break;
                }
            }
        }
        return SUCCESS;
    }

    //1:节目单成员一方信息，2:关联精彩节目播单，3:参赛队伍一方信息，4:关联点播节目播单
    @Override
    public void prepareSave() {
        List<TProgramBase> list = new ArrayList<TProgramBase>();
        TProgramBase temp = null;
        String[] elements = null;
        String[] entryKV = null;

        elements = Struts2Utils.getParameterValues("entity_member");
        for (String element : elements) {
            if (StringUtils.isNotEmpty(element)) {
                entryKV = checkFormat(element).split(":");
                temp = new TProgramBase();
                temp.setFatherId(entity.getId());
                temp.setType(1);
                temp.setKey(Integer.valueOf(entryKV[0]));
                temp.setValue(entryKV[1]);
                list.add(temp);
            }
        }
        elements = Struts2Utils.getParameterValues("entity_exciting_programList");
        for (String element : elements) {
            if (StringUtils.isNotEmpty(element)) {
                temp = new TProgramBase();
                temp.setFatherId(entity.getId());
                temp.setType(2);
                temp.setKey(Integer.valueOf(element));
                temp.setValue("");
                list.add(temp);
            }
        }

        elements = Struts2Utils.getParameterValues("entity_team");
        for (String element : elements) {
            if (StringUtils.isNotEmpty(element)) {
                entryKV = checkFormat(element).split(":");
                temp = new TProgramBase();
                temp.setFatherId(entity.getId());
                temp.setType(3);
                if(entryKV.length > 1){
                    temp.setKey(Integer.valueOf(entryKV[1]));
                }
                temp.setValue(entryKV[0]);
                list.add(temp);
            }
        }


        elements = Struts2Utils.getParameterValues("entity_request_programList");
        for (String element : elements) {
            if (StringUtils.isNotEmpty(element)) {
                temp = new TProgramBase();
                temp.setFatherId(entity.getId());
                temp.setType(4);
                temp.setKey(Integer.valueOf(element));
                temp.setValue("");
                list.add(temp);
            }
        }
        entity.setRelationList(list);
    }


    @Override
    @Action(value = "save")
    public String save() throws Exception {
        boolean editFlag = entity.getId() > 0;
        channelList = channelService.getChannelBaseList();
        String method = editFlag ? InnerApiUtil.PROGRAM_EDIT : InnerApiUtil.PROGRAM_ADD;
        String url = String.format(InnerApiUtil.BASE_URL, method);
        Map<String, Object> headers = new HashMap<String, Object>();
        Map<String, Object> params = new HashMap<String, Object>();
        TSerializer serializer = new TSerializer(new TSimpleJSONProtocol.Factory());
        String programData = serializer.toString(entity);
        headers.put("Sign", InnerApiUtil.TEST_SIGN);
        params.put("data", programData);
        String responseMsg = ApiHttpRequestUtil.forceGetResponseMsg(url, headers, params);
        if (responseMsg == null) {
            addActionMessage("保存失败");
        } else {
            addActionMessage(responseMsg);
        }
        return INPUT;
    }

    @Override
    @Action(value = "delete")
    public String delete() throws Exception {
        String url = String.format(InnerApiUtil.BASE_URL, InnerApiUtil.PROGRAM_DEL);
        Map<String, Object> headers = new HashMap<String, Object>();
        Map<String, Object> params = new HashMap<String, Object>();
        headers.put("Sign", InnerApiUtil.TEST_SIGN);
        params.put("id", Struts2Utils.getParameter("id"));
        String responseMsg = ApiHttpRequestUtil.forceGetResponseCode(url, headers, params);
        if (Constants.CODE_SUC.equals( responseMsg )) {
            code = "A00000";
            message = "删除成功";
        } else {
            code = "A00001";
            message = "id为空";
        }
        renderAjaxMessage(code, message);
        return null;
    }

    @Action(value = "sync")
    public String sync() throws Exception {
        String url = String.format(InnerApiUtil.BASE_URL, InnerApiUtil.PROGRAM_SYNC);
        Map<String, Object> headers = new HashMap<String, Object>();
        Map<String, Object> params = new HashMap<String, Object>();
        headers.put("Sign", InnerApiUtil.TEST_SIGN);
        String responseMsg = ApiHttpRequestUtil.forceGetResponseCode(url, headers, params);
        return null;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public int getFatherId() {
        return fatherId;
    }

    public void setFatherId(int fatherId) {
        this.fatherId = fatherId;
    }

    @Override
    protected void prepareModel() throws Exception {
    }

    public TProgram getEntity() {
        return entity;
    }

    public void setEntity(TProgram entity) {
        this.entity = entity;
    }

    @Override
    public TProgram getModel() {
        return null;
    }

    public List<ChannelBase> getChannelList() {
        return channelList;
    }

    public void setChannelList(List<ChannelBase> channelList) {
        this.channelList = channelList;
    }
}
